from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import InvalidArgumentException, WebDriverException, NoSuchElementException
import time


class Base:
    """
    基础类，封装了selenium基础方法，供page包下面的类继承
    """

    def __init__(self, brower):
        # 打开浏览器，设置driver
        if brower == 'chrome':
            self.driver = webdriver.Chrome()
        elif brower == 'firefox':
            self.driver = webdriver.Firefox()
        elif brower == 'edge':
            self.driver = webdriver.Edge()
        else:
            print('不支持该浏览器')
            self.driver = None

    def get(self, url):
        # 请求目标网址
        try:
            self.driver.get(url)
        except (InvalidArgumentException, WebDriverException):
            print('输入的地址不正确')

    def find_element(self, locator):
        # 定位元素 locator=（element ，value）
        try:
            return self.driver.find_element(*locator)
        except NoSuchElementException:
            print('元素定位失败')

    def click(self, locator):
        # 元素点击操作
        element = self.find_element(locator)
        if element is not None:
            element.click()
        else:
            print('元素定位失败')

    def get_attribute(self, locator, value):
        # 属性定位
        try:
            attribute = self.find_element(locator)
            print(attribute.get_attribute(value))
        except:
            print('属性定位失败')

    #完成common/base.py/Base/浏览器后退/刷新/前进/方法

    def back(self):
        time.sleep(2)
        self.driver.back()

    def forward(self):
        time.sleep(2)
        self.driver.forward()

    def refresh(self):
        time.sleep(2)
        self.driver.refresh()


    def quit(self, seconds=2):
        # 退出浏览器
        time.sleep(seconds)
        self.driver.quit()


if __name__ == '__main__':
    base=Base('chrome')
    base.get('https://www.baidu.com')
    base.find_element(('id','kw'))
    base.get_attribute(('id','kw'),'name')
    time.sleep(2)
    base.back()
    time.sleep(2)
    base.forward()
    time.sleep(2)
    base.refresh()
    base.quit()
